package org.jeecgframework.web.service.impl;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.ContextHolderUtils;
import org.jeecgframework.core.util.DataUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.web.service.CbsVerificationCodeServiceI;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.system.pojo.base.CbsVerificationCodeEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.SendMessage;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("cbsVerificationCodeService")
@Transactional
public class CbsVerificationCodeServiceImpl extends CommonServiceImpl implements CbsVerificationCodeServiceI {

    @Autowired
    SystemService systemService;
    @Autowired
    ZyCommonService zyCommonService;

    public <T> void delete(T entity) {
        super.delete(entity);
        //执行删除操作配置的sql增强
        this.doDelSql((CbsVerificationCodeEntity) entity);
    }

    public <T> Serializable save(T entity) {
        Serializable t = super.save(entity);
        //执行新增操作配置的sql增强
        this.doAddSql((CbsVerificationCodeEntity) entity);
        return t;
    }

    public <T> void saveOrUpdate(T entity) {
        super.saveOrUpdate(entity);
        //执行更新操作配置的sql增强
        this.doUpdateSql((CbsVerificationCodeEntity) entity);
    }

    /**
     * 默认按钮-sql增强-新增操作
     *
     * @param id
     * @return
     */
    public boolean doAddSql(CbsVerificationCodeEntity t) {
        return true;
    }

    /**
     * 默认按钮-sql增强-更新操作
     *
     * @param id
     * @return
     */
    public boolean doUpdateSql(CbsVerificationCodeEntity t) {
        return true;
    }

    /**
     * 默认按钮-sql增强-删除操作
     *
     * @param id
     * @return
     */
    public boolean doDelSql(CbsVerificationCodeEntity t) {
        return true;
    }

    /**
     * 替换sql中的变量
     *
     * @param sql
     * @return
     */
    public String replaceVal(String sql, CbsVerificationCodeEntity t) {
        sql = sql.replace("#{id}", String.valueOf(t.getId()));
        sql = sql.replace("#{session_id}", String.valueOf(t.getSessionId()));
        sql = sql.replace("#{cellphone}", String.valueOf(t.getCellphone()));
        sql = sql.replace("#{randcode}", String.valueOf(t.getRandcode()));
        sql = sql.replace("#{time}", String.valueOf(t.getTime()));
        sql = sql.replace("#{create_name}", String.valueOf(t.getCreateName()));
        sql = sql.replace("#{create_by}", String.valueOf(t.getCreateBy()));
        sql = sql.replace("#{create_date}", String.valueOf(t.getCreateDate()));
        sql = sql.replace("#{update_name}", String.valueOf(t.getUpdateName()));
        sql = sql.replace("#{update_by}", String.valueOf(t.getUpdateBy()));
        sql = sql.replace("#{update_date}", String.valueOf(t.getUpdateDate()));
        sql = sql.replace("#{UUID}", UUID.randomUUID().toString());
        return sql;
    }

    @Override
    public AjaxJson userLoginCheck(String mobilePhone) {
        AjaxJson j = new AjaxJson();
        HttpSession session = ContextHolderUtils.getSession();
        String sessionId = session.getId();
        String randomCode = "";
        AjaxJson rs = zyCommonService.checkUserRandomCodeTimeout(sessionId, StaticValue.RANDOMCODE_LOGIN,null);
        //验证是否验证码是否超时或者是否已经发送过验证码
		if(!rs.isSuccess()){//验证码超时，重新生成
			//验证码 默认 6位数
			String random = String.valueOf(Math.ceil(Math.random()*500000 + 500000));
			randomCode = random.substring(0,random.indexOf("."));
		}else{//验证码未超时 无需重新生成
			randomCode = ((CbsVerificationCodeEntity)rs.getObj()).getRandcode();
		}
        Integer time = StaticValue.SEND_RANDOMCODE_TIMEOUT;
        Map<String, Object> map = new HashMap<String, Object>();
        System.out.println("登录验证码：" + randomCode);
        map.put("verificationCode", randomCode);
        map.put("time", time);
        int callback = SendMessage.sendSMSFTL(mobilePhone, "sms_userlogincheck.ftl", map, systemService);
        if (callback <= 0) {
            j.setSuccess(false);
            j.setMsg("短信发送异常");
        } else {
			if(!rs.isSuccess()){
				if(null == rs.getObj() || rs.getObj().equals(1)){
					CbsVerificationCodeEntity verification = new CbsVerificationCodeEntity();
					verification.setSessionId(sessionId);
					verification.setTime(time);
					verification.setRandcode(randomCode);
					verification.setCellphone(mobilePhone);
					verification.setBusType(StaticValue.RANDOMCODE_LOGIN);
					verification.setCreateDate(new Date());
					super.save(verification);
				}
			}
        }
        return j;
    }


    @Override
    public AjaxJson userRetrievePassword(String mobilePhone) {
        AjaxJson j = new AjaxJson();
        HttpSession session = ContextHolderUtils.getSession();
        Map<String, Object> templeteMap = new HashMap<String, Object>();
        templeteMap.put("phoneLastFour", mobilePhone.substring(7));
        Integer liveTime = StaticValue.SEND_RANDOMCODE_TIMEOUT;
        templeteMap.put("liveTime", liveTime);
        zyCommonService.sendRandomCode(session.getId(), mobilePhone, liveTime, "sms_retrievePassword.ftl", templeteMap, StaticValue.RANDOMCODE_RETRIEVE_PWD);
        return j;
    }

    @Override
    public AjaxJson sendSMSOfAppUserChangePwd(String mobilePhone) {
        AjaxJson j = new AjaxJson();
        HttpSession session = ContextHolderUtils.getSession();
        String sessionId = session.getId();
        String randomCode = "";
        AjaxJson rs = zyCommonService.checkUserRandomCodeTimeout(sessionId, StaticValue.RANDOMCODE_CHANGE_PWD, null);
        //验证是否验证码是否超时或者是否已经发送过验证码
		if(!rs.isSuccess()){//验证码超时，重新生成
			//验证码 默认 6位数
			String random = String.valueOf(Math.ceil(Math.random()*500000 + 500000));
			randomCode = random.substring(0,random.indexOf("."));
		}else{//验证码未超时 无需重新生成
			randomCode = ((CbsVerificationCodeEntity)rs.getObj()).getRandcode();
		}

        Integer time = StaticValue.SEND_RANDOMCODE_TIMEOUT;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("verificationCode", randomCode);
        map.put("time", time);
        map.put("phoneLastFour", mobilePhone.substring(7));
        int callback = SendMessage.sendSMSFTL(mobilePhone, "sms_changePassword.ftl", map, systemService);
        if (callback <= 0) {
            j.setSuccess(false);
            j.setMsg("短信发送异常");
        } else {
			if(!rs.isSuccess()){
				if(null == rs.getObj() || rs.getObj().equals(1)){
					CbsVerificationCodeEntity verification = new CbsVerificationCodeEntity();
					verification.setSessionId(sessionId);
					verification.setTime(time);
					verification.setRandcode(randomCode);
					verification.setCellphone(mobilePhone);
					verification.setBusType(StaticValue.RANDOMCODE_CHANGE_PWD);
					verification.setCreateDate(new Date());
					super.save(verification);
				}
			}
        }
        return j;
    }

    @Override
    public AjaxJson sendSMSOfAppUserChangePhone(String mobilePhone) {
        AjaxJson j = new AjaxJson();
        HttpSession session = ContextHolderUtils.getSession();
        String sessionId = session.getId();
        String randomCode = "";
        AjaxJson rs = zyCommonService.checkUserRandomCodeTimeout(sessionId, StaticValue.RANDOMCODE_CHANGE_PHONE, null);
        //验证是否验证码是否超时或者是否已经发送过验证码
		if(!rs.isSuccess()){//验证码超时，重新生成
			//验证码 默认 6位数
			String random = String.valueOf(Math.ceil(Math.random()*500000 + 500000));
			randomCode = random.substring(0,random.indexOf("."));
		}else{//验证码未超时 无需重新生成
			randomCode = ((CbsVerificationCodeEntity)rs.getObj()).getRandcode();
		}

        Integer time = StaticValue.SEND_RANDOMCODE_TIMEOUT;
        Map<String, Object> map = new HashMap<String, Object>();
        System.out.println("修改手机号短信验证码：" + randomCode);
        map.put("verificationCode", randomCode);
        map.put("time", time);
        int callback = SendMessage.sendSMSFTL(mobilePhone, "sms_changePhone.ftl", map, systemService);
        if (callback <= 0) {
            j.setSuccess(false);
            j.setMsg("短信发送异常");
        } else {
			if(!rs.isSuccess()){
				if(null == rs.getObj() || rs.getObj().equals(1)){
					CbsVerificationCodeEntity verification = new CbsVerificationCodeEntity();
					verification.setSessionId(sessionId);
					verification.setTime(time);
					verification.setRandcode(randomCode);
					verification.setCellphone(mobilePhone);
					verification.setBusType(StaticValue.RANDOMCODE_CHANGE_PHONE);
					verification.setCreateDate(new Date());
					super.save(verification);
				}
			}
        }
        return j;
    }

    @Override
    public boolean checkVerifyCode(String sessionId, String verifyCode) {
        if(StringUtil.isEmpty(verifyCode)){
            return false;
        }
        //TODO 这种验证方式 存在bug， 当一个session 存在多个业务类型的发送验证码会出现问题
        //orig ：dawei ,find : xl
        List<CbsVerificationCodeEntity> codeList = systemService.findHql("from CbsVerificationCodeEntity where sessionId = ? order by createDate desc", sessionId);
        if (codeList.size() > 0) {
            long dif = (DataUtils.getDate().getTime() - codeList.get(0).getCreateDate().getTime()) / 1000;
            if (dif <= codeList.get(0).getTime() && codeList.get(0).getRandcode().equals(verifyCode)) {
                return true;
            }
        }
        return false;
    }
}